package com.pocketsweet.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLInfoChangeNotify;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.SelfFragment;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.FlowLayout;
import com.pocketsweet.ui.uilib.GalleryView;
import com.pocketsweet.ui.uilib.GalleryView.IImagePickerListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.SpecialTagView;
import com.pocketsweet.ui.uilib.adapter.VoiceAdapter;
import com.pocketsweet.ui.uilib.wheelcity.wheelCity;
import com.pocketsweet.ui.uilib.wheelview.ScreenInfo;
import com.pocketsweet.ui.uilib.wheelview.WheelMain;
import com.pocketsweet.utils.PhotoUtil;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;
import com.pocketsweet.utils.selectPicUtils;

@ContentView(R.layout.activity_profile_edit)
public class ProfileEdit extends BaseActivity implements OnClickListener,
        IImagePickerListener {

    @ViewInject(R.id.mainHeader)
    private static HeaderLayout header;

    @ViewInject(R.id.tvLoading)
    private static TextView tvLoading;

    @ViewInject(R.id.tvUserAge)
    private static TextView tvUserAge;

    @ViewInject(R.id.tvNickname)
    private static TextView tvNickname;

    @ViewInject(R.id.tvBirthdayData)
    private static TextView tvBirthday;

    @ViewInject(R.id.tvCity)
    private static TextView tvCity;

    @ViewInject(R.id.tvApperence)
    private static TextView tvApperence;

    @ViewInject(R.id.tvFrom)
    private static TextView tvFrom;

    @ViewInject(R.id.tvStar)
    private static TextView tvStar;

    @ViewInject(R.id.linOtherView)
    private static LinearLayout linOtherView;

    @ViewInject(R.id.llLike)
    private static LinearLayout llLike;

    @ViewInject(R.id.linCity)
    private static LinearLayout linCity;

    @ViewInject(R.id.llReport)
    private static LinearLayout llReport;

    @ViewInject(R.id.linCall)
    private static LinearLayout linCall;

    @ViewInject(R.id.linBirthday)
    private static LinearLayout linBirthday;

    @ViewInject(R.id.linMolianNumber)
    private static LinearLayout linMolianNumber;

    @ViewInject(R.id.linSign)
    private static LinearLayout linSign;

    @ViewInject(R.id.linBelong)
    private static LinearLayout linBelong;

    @ViewInject(R.id.linCallMe)
    private static LinearLayout linCallMe;

    @ViewInject(R.id.linSpecical)
    private static LinearLayout linSpecical;

    @ViewInject(R.id.linLike)
    private static LinearLayout linLike;

    @ViewInject(R.id.linLook)
    private static LinearLayout linLook;

    @ViewInject(R.id.linJob)
    private static LinearLayout linJob;

    @ViewInject(R.id.linLanguage)
    private static LinearLayout linLanguage;

    @ViewInject(R.id.linVoice)
    private static LinearLayout linVoice;

    @ViewInject(R.id.linNickname)
    private static LinearLayout linNickname;

    @ViewInject(R.id.tvSign)
    private static TextView tvSign;

    @ViewInject(R.id.tvBelong)
    private static TextView tvBelong;

    @ViewInject(R.id.tvCallMe)
    private static TextView tvCallMe;

    @ViewInject(R.id.tvHeight)
    private static TextView tvHeight;

    @ViewInject(R.id.tvWeight)
    private static TextView tvWeight;

    @ViewInject(R.id.tvFigure)
    private static TextView tvFigure;

    // @ViewInject(R.id.tvSpecial)
    // private static TextView tvSpecial;

    @ViewInject(R.id.tvLanguage)
    private static TextView tvLanguage;

    @ViewInject(R.id.flowLike)
    private static FlowLayout flowLike;

    @ViewInject(R.id.flowSpecial)
    private static FlowLayout flowSpecial;
    //
    // @ViewInject(R.id.tvLike)
    // private static TextView tvLike;

    @ViewInject(R.id.tvJob)
    private static TextView tvJob;

    @ViewInject(R.id.voiceListView)
    private static ListView voiceListView;
    private ArrayList<String> specialList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
    private ArrayList<String> likeList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
    private VoiceAdapter voiceAdapter;
    private MLUser mlUser = new MLUser();
    private GalleryView mGalleryView;
    private ProgressBar progressBar;
    private TextView progressBarText;
    // private MLGallery mGallery;
    // public List<String> mImagePaths;// 相册原有图片的路径，上传时候比较避免重复上传
    // private List<AVFile> mlAVFileList = new LinkedList<AVFile>();
    private AVFile photo;
    private ArrayList<String> willingList; // 将值传给编辑页面，编辑页面不用再请求网络
    private String location;
    WheelMain wheelMain;
    private ArrayList<String> languageList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络

    // private List<AVFile> mCmpAVFileList = new LinkedList<AVFile>();//
    // 删除时对比的文件列表
    // 删除后需要更新的列表
    private Uri cropPath;
    private LoadingDailog mLoadingDialog;
    private int i; // 图片计数

    private static final int REQUEST_CODE_SELECT_AVATAR = 0x01;
    private static final int REQUEST_CODE_SELECT_PHOTO = 0x02;
    private static final int REQUEST_CODE_EDIT = 0x03;
    private static final int REQUEST_CROP = 0x04;

    public static boolean needUpdate = false;
    private int score = 0;// 资料完整度
    boolean isTask;
    public static boolean hasNotify = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        Intent intent = getIntent();
        // mImagePaths = intent.getStringArrayListExtra("imgsPath");
        // mImagePaths = SelfFragment.imgsPath;
        mlUser = UserService.getCurrentUser();
        mLoadingDialog = ToolKits.createLoadingDialog(ProfileEdit.this, "上传中");
        initView();
        setHeaderFunction();
    }

    private void initView() {
        voiceAdapter = new VoiceAdapter(ProfileEdit.this, Main.voiceList, false);
        voiceListView.setCacheColorHint(0);
        linBelong.setOnClickListener(this);
        linCallMe.setOnClickListener(this);
        linVoice.setOnClickListener(this);
        linNickname.setOnClickListener(this);
        linSign.setOnClickListener(this);
        linBirthday.setOnClickListener(this);
        linCity.setOnClickListener(this);
        linLook.setOnClickListener(this);
        linJob.setOnClickListener(this);
        linLike.setOnClickListener(this);
        linSpecical.setOnClickListener(this);
        linLanguage.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initVoice();
        // setScoreTest();// 强制将分数变100，用来测试完善资料的任务，之后要删掉。
    }

    @Override
    public void onPause() {
        super.onPause();
        if (Main.MediaTimer != null && Main.mMediaPlayer.isPlaying()) {
            Main.mMediaPlayer.pause();
            Main.mMediaPlayer.stop();
            Main.mMediaPlayer.reset();
            Main.MediaTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 如果有头像，城市，昵称，年龄的修改则通知资料
        if (needUpdate == true) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("touserIds", MLCache.getAllChatId());
            params.put("fromuserId", UserService.getCurrentUserId());
            AVCloud.callFunctionInBackground("sendUpdateMsg", params, null);
            needUpdate = false;
        }
        hasNotify = false;
        MLApplication.getInstance().removeActivity(this);

    }

    public static void notifyBack() {
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            return;
        }
        // 恋爱体验师修改资料才会执行相关操作
        if (hasNotify != true) {
            int status = 0;
            if (UserService.getCurrentUser().getStatus() == C.USER_STATUS_BADINFO) {
                status = 1;
            }
            MLInfoChangeNotify notify = new MLInfoChangeNotify();
            notify.setStatus(status);
            notify.setUser(UserService.getCurrentUser());
            notify.saveInBackground(new SaveCallback() {

                @Override
                public void done(AVException e) {
                    if (e == null) {
                        hasNotify = true;
                    }
                }
            });

        }
    }

    private void initVoice() {
        // if (Main.voiceList == null) {
        mlUser = UserService.getCurrentUser();
        final AVQuery<MLVoice> query = new AVQuery<MLVoice>("MLVoice");
        query.whereEqualTo("belong_to", mlUser);
        query.findInBackground(new FindCallback<MLVoice>() {
            @Override
            public void done(List<MLVoice> list, AVException arg1) {
                if (arg1 == null) {
                    Main.voiceList.clear();
                    if (list.size() > 0) {
                        // for (MLVoice temp : list) {
                        Main.voiceList.add(list.get(list.size() - 1));
                        // }
                        voiceAdapter.notifyDataSetChanged();
                    }
                    initUserInfo();
                } else {
                    initUserInfo();
                    // Log.e("＝＝错误", "查询错误: " + arg1.getMessage());

                }
            }
        });
        // }
    }

    private void initUserInfo() {
        isTask = getIntent().getBooleanExtra("task", false);
        mlUser = UserService.getCurrentUser();
        if (mlUser == null) {
            return;
        }
        if (!StringUtils.isEmpty(mlUser.getIntro())) {
            tvSign.setText(mlUser.getIntro());
        } else {
            tvSign.setText("");
        }
        if (!StringUtils.isEmpty(mlUser.getNickname())) {
            tvNickname.setText(mlUser.getNickname());
        } else {
            tvNickname.setText("");
        }
        if (mlUser.getBirthday() != null && !StringUtils.isEmpty(mlUser.getBirthday().toString())) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            tvBirthday.setText(format.format(mlUser.getBirthday()));
        } else {
            tvBirthday.setText(" ");
        }
        String location = mlUser.getLocationCity();
        if (StringUtils.isEmpty(location)) {
            location = mlUser.getLocationProvince();
        }
        if (StringUtils.isEmpty(location)) {
            location = "";
        }
        tvCity.setText(location + " ");
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getHeight()))
                && !String.valueOf(mlUser.getHeight()).equals("0")) {
            tvHeight.setText(String.valueOf(mlUser.getHeight()) + "cm");
            tvHeight.setVisibility(View.VISIBLE);
        } else {
            tvHeight.setText("");
            tvHeight.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getWeight()))
                && !String.valueOf(mlUser.getWeight()).equals("0")) {
            tvWeight.setText(String.valueOf(mlUser.getWeight()) + "kg");
            tvWeight.setVisibility(View.VISIBLE);
        } else {
            tvWeight.setText("");
            tvWeight.setVisibility(View.GONE);

        }
        if (!StringUtils.isEmpty(mlUser.getFigure())) {
            tvApperence.setVisibility(View.VISIBLE);

            tvApperence.setText(mlUser.getFigure());
        } else {
            tvApperence.setText("");
            tvApperence.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(mlUser.getJob())) {
            tvJob.setText(mlUser.getJob());
        } else {
            tvJob.setText("");
        }
        // if (mlUser.getLikeTags() != null && mlUser.getLikeTags().size() > 0)
        // {
        // StringBuffer like = new StringBuffer();
        // for (String tempLike : mlUser.getLikeTags()) {
        // like.append(tempLike + " ");
        // }
        // tvLike.setText(like);
        // } else {
        // tvLike.setText("");
        // }
        specialList.clear();
        if (mlUser.getSpecial() != null && mlUser.getSpecial().size() > 0) {
            for (String like : mlUser.getSpecial()) {
                specialList.add(like);
            }
        }
        initSpecialTag();
        likeList.clear();
        if (mlUser.getLikeTags() != null && mlUser.getLikeTags().size() > 0) {
            for (String like : mlUser.getLikeTags()) {
                likeList.add(like);
            }
        }
        initlikeTag();
        if (mlUser.getLanguage() != null && mlUser.getLanguage().size() > 0) {
            StringBuffer language = new StringBuffer();
            for (String temp : mlUser.getLanguage()) {
                languageList.add(temp);
                language.append(temp + " ");
            }
            tvLanguage.setText(language);
        } else {
            tvLanguage.setText("");
        }
        voiceAdapter.notifyDataSetChanged();
        voiceListView.setAdapter(voiceAdapter);
        if (!StringUtils.isEmpty(mlUser.getBelong())) {
            tvBelong.setText(mlUser.getBelong());
        }
        if (mlUser.getCalledTags() != null && mlUser.getCalledTags().size() > 0) {
            StringBuffer called = new StringBuffer();
            for (String temp : mlUser.getCalledTags()) {
                called.append(temp + " ");
            }
            tvCallMe.setText(called);
        } else {
            tvCallMe.setText("");
        }
        // if (mlUser.getSpecial() != null && mlUser.getSpecial().size() > 0) {
        // StringBuffer special = new StringBuffer();
        // for (String tempLike : mlUser.getSpecial()) {
        // special.append(tempLike + " ");
        // }
        // tvSpecial.setText(special);
        // }
        // if (mlUser.getWillingTags() != null
        // && mlUser.getWillingTags().size() > 0) {
        // specialList = new ArrayList<String>();
        // for (String temp : mlUser.getWillingTags()) {
        // specialList.add(temp);
        // }
        // initWillingTag(specialList);
        // } else {
        // willingTag.removeAllViews();
        // }
        mGalleryView = (GalleryView) findViewById(R.id.userGallery);
        mGalleryView.setImagePickerListener(this);
        if (SelfFragment.mlAVFileList != null
                && SelfFragment.mlAVFileList.size() > 0 && isTask == false) {
            // Log.e("==", "has photo");
            for (int i = 0; i < SelfFragment.mlAVFileList.size(); i++) { // 获取相册
                if (SelfFragment.mlAVFileList != null
                        && SelfFragment.mlAVFileList.get(i) != null
                        && SelfFragment.mlAVFileList.get(i).getUrl() != null) {
                    mGalleryView.addImagePath(SelfFragment.mlAVFileList.get(i)
                            .getUrl());
                }
            }
            // mGallery = SelfFragment.mGallery;
            // SelfFragment.imgsPath = mGalleryView.getImagePaths();
            score = UserService.getUserProfileIntegrity(SelfFragment.imgsPath
                    .size());
            progressBarText = (TextView) findViewById(R.id.progressBarText);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            progressBar.setProgress(score);
            progressBarText.setText(score + "%");
            setCompleteProfile();
        } else { // 如果该用户没有相册，则创建
            // Log.e("==", "create photo");
            AVQuery<MLGallery> query = new AVQuery<MLGallery>("MLGallery");
            query.whereEqualTo("belong_to", mlUser);
            query.include("images");
            query.findInBackground(new FindCallback<MLGallery>() {
                public void done(List<MLGallery> gallery, AVException e) {
                    if (e == null) {
                        SelfFragment.mGallery = gallery.get(0);
                        SelfFragment.mlAVFileList = SelfFragment.mGallery
                                .getImages();
                        if (SelfFragment.mlAVFileList != null) {
                            for (int i = 0; i < SelfFragment.mlAVFileList
                                    .size(); i++) { // 获取相册
                                mGalleryView
                                        .addImagePath(SelfFragment.mlAVFileList
                                                .get(i).getUrl());
                            }
                            SelfFragment.imgsPath = mGalleryView
                                    .getImagePaths();
                        } else {
                        }
                        // 更新资料完整度
                        score = UserService
                                .getUserProfileIntegrity(SelfFragment.imgsPath
                                        .size());
                        // score = UserService.getUserProfileIntegrity(7);//
                        // 测试，要删掉
                        progressBarText = (TextView) findViewById(R.id.progressBarText);
                        progressBar = (ProgressBar) findViewById(R.id.progressBar);
                        progressBar.setProgress(score);
                        progressBarText.setText(score + "%");
                        setCompleteProfile();
                    } else {
                        // 没有相册的处理
                        SelfFragment.mGallery = new MLGallery();
                        if (SelfFragment.imgsPath == null
                                || SelfFragment.imgsPath.size() == 0) {// 之前注册的用户没把头像加入MLGallery，先把头像也加入MLGallery，以后可删除这几句。
                            if (SelfFragment.imgsPath == null) {
                                SelfFragment.imgsPath = new ArrayList<String>();
                            }
                            mLoadingDialog.show();
                            SelfFragment.mGallery.add("images",
                                    mlUser.getAvatar());
                            SelfFragment.mGallery
                                    .saveInBackground(new SaveCallback() {

                                        @Override
                                        public void done(AVException arg0) {
                                            mLoadingDialog.dismiss();
                                            if (arg0 == null) {
                                                mGalleryView.addImagePath(mlUser
                                                        .getAvatarUrl());
                                                SelfFragment.imgsPath.add(mlUser
                                                        .getAvatarUrl());
                                                SelfFragment.mlAVFileList
                                                        .add(mlUser.getAvatar());
                                            } else {
                                            }
                                            // 更新资料完整度
                                            score = UserService
                                                    .getUserProfileIntegrity(SelfFragment.imgsPath
                                                            .size());
                                            // score =
                                            // UserService.getUserProfileIntegrity(7);//
                                            // 测试，要删掉
                                            progressBarText = (TextView) findViewById(R.id.progressBarText);
                                            progressBar = (ProgressBar) findViewById(R.id.progressBar);
                                            progressBar.setProgress(score);
                                            progressBarText
                                                    .setText(score + "%");
                                            setCompleteProfile();
                                        }
                                    });
                        }
                    }
                }
            });
        }
    }

    private void initSpecialTag() {
        flowSpecial.clearAllViews();
        for (int i = 0; i < specialList.size(); i++) {
            final SpecialTagView itemView = new SpecialTagView(ProfileEdit.this);
            itemView.initBgColor(R.drawable.shape_rectangle_gray_fill);
            itemView.setText(specialList.get(i));
            flowSpecial.addView(itemView);

        }
    }

    private void initlikeTag() {
        flowLike.clearAllViews();
        for (int i = 0; i < likeList.size(); i++) {
            final SpecialTagView itemView = new SpecialTagView(ProfileEdit.this);
            itemView.initBgColor(R.drawable.shape_rectangle_gray_fill);
            itemView.setText(likeList.get(i));
            flowLike.addView(itemView);

        }
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setRightText("");
        header.setMiddleText("我的资料");
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                if (mLoadingDialog.isShowing()) {
                    mLoadingDialog.dismiss();
                }
                ProfileEdit.this.finish();
            }
        });
    }

    private void setCompleteProfile() {// 设置完善资料的任务完成情况
        // Log.e("==finish", "save task finish");
        // score = 100;//强制将分数变100，用来测试完善资料的任务，之后要删掉。
        // score = UserService.getUserProfileIntegrity(mImagePaths
        // .size());
        if (score == 100
                && MLContext.getTask(MLContext.TASK_CONSUMMATE) != C.TASK_FINISH) { // 如果资料完整和任务未领取，则可领取任务
            MLContext.saveTask(MLContext.TASK_CONSUMMATE, C.TASK_GET_REWARD);
        } else if (score < 100
                && MLContext.getTask(MLContext.TASK_CONSUMMATE) != C.TASK_FINISH) {// 如果资料不完整和任务未领取，则设置任务未完成
            MLContext.saveTask(MLContext.TASK_CONSUMMATE, C.TASK_UNFINISH);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case selectPicUtils.GET_IMAGE_BY_CAMERA: // 拍照上传
                Uri url = selectPicUtils.imageUriFromCamera;
                if (url != null) {
                    String sImagePath = ToolKits.getImgRealPathFromURI(url,
                            ProfileEdit.this);
                    String copressPath = sImagePath + "_small";
                    WindowManager wm = (WindowManager) ProfileEdit.this
                            .getSystemService(Context.WINDOW_SERVICE);
                    int width = wm.getDefaultDisplay().getWidth();
                    selectPicUtils.cropBgImage(ProfileEdit.this,
                            selectPicUtils.imageUriFromCamera, 1, 1, 600, 600);
                }
                break;
            case REQUEST_CODE_SELECT_PHOTO: // 选择图片上传,每次上传一个图片，就会上传到服务器,但是未保存到MLUser

                if (null != data) {
                    Uri url1 = data.getData();
                    if (url1 != null) {
                        String ImagePath = ToolKits.getImgRealPathFromURI(url1,
                                ProfileEdit.this);
                        File file = new File(ImagePath);
                        cropPath = Uri.parse("file://" + file.getAbsolutePath()
                                + "_small.png");
                        startPhotoZoom(Uri.fromFile(file));
                    }
                }
                break;
            case selectPicUtils.CROP_IMAGE: // 拍照后的回调
                if (selectPicUtils.cropImageUri != null) {
                    File avatarCrop = selectPicUtils.createFileFromUri(
                            selectPicUtils.cropImageUri, ProfileEdit.this);
                    // UserService.displayAvatar(
                    // "file://" + avatarCrop.getAbsolutePath(), ivAvatar);
                    try {
                        String copressPath = avatarCrop.getAbsolutePath()
                                + "_small";
                        PhotoUtil.compressImage(avatarCrop.getAbsolutePath(),
                                copressPath);
                        photo = AVFile.withAbsoluteLocalPath(avatarCrop.getName(),
                                copressPath);
                        mLoadingDialog.show();
                        photo.saveInBackground(new SaveCallback() { // 先保存照片到_File
                            @Override
                            public void done(AVException arg0) {
                                if (arg0 == null) {
                                    SelfFragment.mGallery.add("images", photo);
                                    SelfFragment.mGallery
                                            .saveInBackground(new SaveCallback() { // 再保存照片到MLGallery

                                                @Override
                                                public void done(AVException e) {
                                                    if (e == null) {
                                                        score = score + 5;
                                                        progressBar
                                                                .setProgress(score);
                                                        progressBarText
                                                                .setText(score
                                                                        + "%");
                                                        setCompleteProfile();
                                                        mGalleryView
                                                                .addImagePath(photo
                                                                        .getUrl());
                                                        if (isTask == false) {
                                                            SelfFragment.imgsPath.add(photo
                                                                    .getUrl());
                                                        }
                                                        SelfFragment.mlAVFileList
                                                                .add(photo);
                                                        mLoadingDialog.dismiss();
                                                        initUserInfo();
                                                        // ToolKits.toast(
                                                        // UserProfileEdit.this,
                                                        // "保存成功");
                                                        // mAVFileList.clear(); //
                                                        // 清空待上传的图片
                                                    } else {
                                                        mLoadingDialog.dismiss();
                                                        ToolKits.toast(
                                                                ProfileEdit.this,
                                                                "保存失败");
                                                        // Log.e("==eeror",
                                                        // "save photo error:"
                                                        // + e.getCode()
                                                        // + e.getMessage());
                                                    }

                                                }
                                            });
                                }
                            }
                        });
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_CROP: // 选择图片后的回调
                if (cropPath == null) {
                    return;
                }
                String ImagePath = ToolKits.getImgRealPathFromURI(cropPath,
                        ProfileEdit.this);
                String copressPath = ImagePath + "_small";
                PhotoUtil.compressImage(ImagePath, copressPath);
                File file = new File(copressPath);
                if (file.exists()) {
                    try {
                        photo = AVFile.withAbsoluteLocalPath(file.getName(),
                                file.getAbsolutePath());
                        mLoadingDialog.show();
                        photo.saveInBackground(new SaveCallback() { // 先保存照片到_File
                            @Override
                            public void done(AVException arg0) {
                                if (arg0 == null) {
                                    SelfFragment.mGallery.add("images", photo);
                                    SelfFragment.mGallery
                                            .saveInBackground(new SaveCallback() { // 再保存照片到MLGallery

                                                @Override
                                                public void done(AVException e) {
                                                    if (e == null) {
                                                        score = score + 5;
                                                        progressBar
                                                                .setProgress(score);
                                                        progressBarText
                                                                .setText(score
                                                                        + "%");
                                                        setCompleteProfile();
//													Log.e("==",
//															"add photos request");
                                                        mGalleryView
                                                                .addImagePath(photo
                                                                        .getUrl()); // 图片需要显示到界面上
                                                        if (isTask == false) {

                                                            SelfFragment.imgsPath.add(photo
                                                                    .getUrl());
                                                        }
                                                        SelfFragment.mlAVFileList
                                                                .add(photo);
                                                        mLoadingDialog.dismiss();
                                                        ToolKits.toast(
                                                                ProfileEdit.this,
                                                                "保存成功");
                                                        // mAVFileList.clear(); //
                                                        // 清空待上传的图片
                                                    } else {
                                                        mLoadingDialog.dismiss();
                                                        ToolKits.toast(
                                                                ProfileEdit.this,
                                                                "保存失败");
                                                        // Log.e("==eeror",
                                                        // "save photo error:"
                                                        // + e.getCode()
                                                        // + e.getMessage());
                                                    }

                                                }
                                            });
                                }
                            }
                        });
                        // mGalleryView.addImagePath(ImagePath);// 先显示图片，不上传
                        // mAVFileList.add(photo);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToolKits.toast(ProfileEdit.this, "文件不存在！");
                }
            default:
                break;
        }
        if (requestCode == REQUEST_CODE_SELECT_PHOTO) {

        }
    }

    /*
     * 添加图片
     */
    public void addPhoto() {
        new ActionSheetDialog(ProfileEdit.this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("从相册选择", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent();
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(intent,
                                        REQUEST_CODE_SELECT_PHOTO);
                                // selectPicUtils.openLocalImage(getActivity());
                            }
                        })
                .addSheetItem("拍照", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                selectPicUtils
                                        .openCameraImage(ProfileEdit.this);
                            }
                        }).show();
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        WindowManager wm = (WindowManager) ProfileEdit.this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropPath);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, REQUEST_CROP);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.linBelong:
                Intent intent = new Intent(this, EditBelong.class);
                intent.putExtra("belong", mlUser.getBelong());
                startActivity(intent);
                break;
            case R.id.linCallMe:
                Intent intent2 = new Intent(this, EditCalled.class);
                startActivity(intent2);
                break;
            case R.id.linVoice:
                Intent intent4 = new Intent(this, EditUserVoice.class);
                startActivity(intent4);
                break;
            // case R.id.linWantU:
            // Intent intent5 = new Intent(this, EditWilling.class);
            // startActivity(intent5);
            // break;
            case R.id.linNickname:
                Intent intentlinNickname = new Intent(ProfileEdit.this,
                        EditNickName.class);
                intentlinNickname.putExtra("nickname", mlUser.getNickname());
                startActivity(intentlinNickname);
                break;
            case R.id.linSign:
                Intent intent1 = new Intent(ProfileEdit.this, EditSign.class);
                intent1.putExtra("sign", mlUser.getIntro());
                startActivity(intent1);
                break;
            case R.id.linCity:
                final wheelCity myWheelCity = new wheelCity(ProfileEdit.this);
                View cityview = myWheelCity.getView();
                final MyAlertDialog dialog1 = new MyAlertDialog(ProfileEdit.this)
                        .builder().setTitle("城市选择").setView(cityview)
                        .setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                dialog1.setPositiveButton("确定", new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (myWheelCity.getProvinceText().equals("未设定") || myWheelCity.getCityText().equals("未设定")) {
                            Toast.makeText(ProfileEdit.this, "您还未选择城市", 1).show();
                            return;
                        }
                        if (!myWheelCity.getProvinceText().equals("未设定")) {
                            mlUser.setLocationProvince(myWheelCity
                                    .getProvinceText());
                            // if (!location.equals(myWheelCity.getProvinceText()))
                            // {
                            ProfileEdit.needUpdate = true;
                            // }
                            location = myWheelCity.getProvinceText();
                        }
                        if (!myWheelCity.getCityText().equals("未设定")) {
                            mlUser.setLocationCity(myWheelCity.getCityText());
                            location = myWheelCity.getCityText();
                        }
                        // if (!myWheelCity.getCountryText().equals("未设定")) {
                        // mlUser.setLocationDistrict(myWheelCity.getCountryText());
                        // }
                        mlUser.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(AVException e) {
                                // TODO Auto-generated method stub
                                if (e == null) {
                                    tvCity.setText(location);

                                } else {
                                }
                            }
                        });
                        Toast.makeText(ProfileEdit.this, "保存成功", 1).show();

                    }
                });
                dialog1.show();
                break;
            case R.id.linBirthday:
                LayoutInflater inflater1 = LayoutInflater.from(ProfileEdit.this);
                final View timepickerview1 = inflater1.inflate(R.layout.timepicker,
                        null);
                ScreenInfo screenInfo1 = new ScreenInfo(ProfileEdit.this);
                wheelMain = new WheelMain(timepickerview1);
                wheelMain.screenheight = screenInfo1.getHeight();
                Calendar calendar1 = Calendar.getInstance();
                int year1 = calendar1.get(Calendar.YEAR);
                int month1 = calendar1.get(Calendar.MONTH);
                int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
                wheelMain.initDateTimePicker(year1, month1, day1);
                final MyAlertDialog dialog = new MyAlertDialog(ProfileEdit.this)
                        .builder().setTitle("生日选择").setView(timepickerview1)
                        .setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                dialog.setPositiveButton("确定", new OnClickListener() {
                    @SuppressLint("SimpleDateFormat")
                    @Override
                    public void onClick(View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = null;
                        try {
                            date = sdf.parse(wheelMain.getTime());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        mlUser.setBirthday(date);
                        mlUser.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    SimpleDateFormat format = new SimpleDateFormat(
                                            "yyyy-MM-dd");
                                    tvBirthday.setText(format.format(mlUser
                                            .getBirthday()));

                                } else {
                                }
                            }
                        });
                        Toast.makeText(ProfileEdit.this, "保存成功", 1).show();
                    }
                });
                dialog.show();
                break;
            case R.id.linLook:
                Intent intentlinLook = new Intent(ProfileEdit.this,
                        EditApperance.class);
                intentlinLook.putExtra("figure", mlUser.getFigure());
                startActivity(intentlinLook);
                break;
            case R.id.linJob:
                Intent intent3 = new Intent(ProfileEdit.this, EditJob.class);
                intent3.putExtra("job", mlUser.getJob());
                startActivity(intent3);
                break;
            case R.id.linLike:
                Intent intentlinLike = new Intent(ProfileEdit.this, EditLike.class);
                startActivity(intentlinLike);
                break;
            case R.id.linUnlike:
                Intent intent5 = new Intent(ProfileEdit.this, EditUnLike.class);
                startActivity(intent5);
                break;
            case R.id.linLanguage:
                Intent intent6 = new Intent(ProfileEdit.this, EditLanguage.class);
                intent6.putStringArrayListExtra("language", languageList);
                startActivity(intent6);
                break;
            case R.id.linSpecical:
                Intent intentlinSpecical = new Intent(ProfileEdit.this,
                        EditSpecial.class);
                startActivity(intentlinSpecical);
                break;
        }

    }

    @Override
    public void onImagePickerAddButtonClick() {
        addPhoto();
        // Intent intent = new Intent();
        // intent.setType("image/*");
        // intent.setAction(Intent.ACTION_GET_CONTENT);
        // startActivityForResult(intent, REQUEST_CODE_SELECT_PHOTO);
    }

    @Override
    public void onImagePickerItemClick(int position, View view) {
        Intent imgintent = new Intent(this, PictureViewActivity.class);
        @SuppressWarnings("rawtypes")
        ArrayList<String> mBigImagePath = new ArrayList<String>();
        mBigImagePath.addAll(SelfFragment.imgsPath);
        imgintent.putStringArrayListExtra("ImageList", mBigImagePath);
        imgintent.putExtra("index", position);
        startActivity(imgintent);
    }

    @Override
    public void onImagePickerItemLongClick(final int position) {
        // 长按事件删除
        if (position < 0 || SelfFragment.imgsPath == null || mlUser.getAvatarUrl() == null || SelfFragment.imgsPath.size() <= 0 || position >= SelfFragment.imgsPath.size()) {
            return;
        }
        if (mlUser.getAvatarUrl().equals(SelfFragment.imgsPath.get(position))) { // 头像不可删除
            return;
        }
        // Log.e("==SelfFragment.imgsPath", "SelfFragment.imgsPath:"
        // + SelfFragment.imgsPath.size());
        new ActionSheetDialog(ProfileEdit.this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("删除图片", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                AlertDialog.Builder dialog = new AlertDialog.Builder(
                                        ProfileEdit.this);
                                dialog.setTitle("提示")
                                        .setIcon(
                                                android.R.drawable.ic_dialog_info)
                                        .setMessage("您是否要移除该相片？")
                                        .setPositiveButton(
                                                "确定",
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int which) {
                                                        score = score - 5;
                                                        progressBar
                                                                .setProgress(score);
                                                        progressBarText
                                                                .setText(score
                                                                        + "%");
                                                        setCompleteProfile();
                                                        // 移除相片
                                                        AVQuery<AVObject> query = AVQuery
                                                                .getQuery("_File");// 删掉_File文件
                                                        query.whereEqualTo(
                                                                "objectId",
                                                                SelfFragment.mlAVFileList
                                                                        .get(position)
                                                                        .getObjectId()
                                                                        .toString());
                                                        query.deleteAllInBackground(null);
                                                        mGalleryView
                                                                .removeImagePath(position);
                                                        SelfFragment.mlAVFileList
                                                                .remove(position);
                                                        // Log.e("==SelfFragment.imgsPath",
                                                        // "SelfFragment.imgsPath:"
                                                        // +
                                                        // SelfFragment.imgsPath
                                                        // .size());
                                                        if (isTask == false) {
                                                            SelfFragment.imgsPath
                                                                    .remove(position);
                                                        }
                                                        SelfFragment.mGallery
                                                                .setImage(SelfFragment.mlAVFileList);
                                                        SelfFragment.mGallery
                                                                .saveInBackground();
                                                        ProfileEdit.needUpdate = true;

                                                    }
                                                })
                                        .setNegativeButton(
                                                "取消",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int which) {
                                                        dialog.cancel();// 取消弹出框
                                                    }
                                                }).create().show();
                            }
                        })
                .addSheetItem("设置为头像", SheetItemColor.Gray,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // TODO
                                mLoadingDialog.setText("加载中");
                                mLoadingDialog.show();
                                mlUser.setAvatar(SelfFragment.mlAVFileList
                                        .get(position));
                                mlUser.setSubAvatar(SelfFragment.mlAVFileList
                                        .get(position).getThumbnailUrl(true,
                                                100, 100));
                                mlUser.saveInBackground(new SaveCallback() {

                                    @Override
                                    public void done(AVException arg0) {
                                        // TODO Auto-generated method stub
                                        mLoadingDialog.dismiss();
                                        if (arg0 == null) {
                                            mGalleryView.notifyDataSetChanged();// 更新当前头像标签的位置
                                            needUpdate = true;
                                            ProfileEdit.needUpdate = true;
                                            SelfFragment.needUpdateAvatar = true;
                                            ToolKits.toast(ProfileEdit.this,
                                                    "头像设置成功");
                                            // 告知本地头像需更新
                                            MLCache.getCache()
                                                    .put(UserService
                                                                    .getCurrentUserId(),
                                                            UserService
                                                                    .getCurrentUser()
                                                                    .toJSONObject());
                                        } else {
                                            // Log.e("==error",
                                            // "can not save avatar");
                                        }
                                    }
                                });
                            }
                        }).show();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}
